<template>
  <!-- 讯飞AI助手悬浮按钮 -->
    <div class="xunfei-ai-assistant">
    <!-- 讯飞AI助手悬浮按钮 -->
    <transition name="fade">
      <div 
        v-if="!isOpen"
        class="ai-float-button"
        @click.stop="toggleAI"
        @mousedown="console.log('鼠标按下事件触发')"
        @mouseup="console.log('鼠标释放事件触发')"
        @touchstart="console.log('触摸开始事件触发')"
        @touchend="console.log('触摸结束事件触发')"
        title="点击打开AI助手"
      >
        <div class="ai-icon">
          <svg viewBox="0 0 24 24" fill="currentColor">
            <path d="M2 18v2h20v-2H2zm1-3h18l1-5H2l1 5zM4 8l1-5h14l1 5H4z"/>
          </svg>
        </div>
        <div class="ai-pulse"></div>
        <div class="ai-status-indicator" :class="{ connected: isConnected }"></div>
      </div>
    </transition>

    <!-- AI对话面板 -->
    <transition name="slide-fade">
      <div v-if="isOpen" class="ai-chat-panel">
        <!-- 面板头部 -->
        <div class="panel-header">
          <div class="header-title">
            <div class="ai-avatar">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M2 18v2h20v-2H2zm1-3h18l1-5H2l1 5zM4 8l1-5h14l1 5H4z"/>
              </svg>
            </div>
            <span>鞋城AI助手</span>
          </div>
          <div class="header-actions">
            <button @click="closeAI" class="close-btn" title="关闭">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
              </svg>
            </button>
          </div>
        </div>

        <!-- 聊天内容区 -->
        <div class="chat-content">
          <div class="messages-container" ref="messagesContainer">
            <div 
              v-for="(message, index) in messages" 
              :key="index"
              class="message-item"
              :class="{ 'user-message': message.isUser, 'ai-message': !message.isUser }"
            >
              <div class="message-avatar">
                <svg v-if="message.isUser" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
                </svg>
                <svg v-else viewBox="0 0 24 24" fill="currentColor">
                  <path d="M2 18v2h20v-2H2zm1-3h18l1-5H2l1 5zM4 8l1-5h14l1 5H4z"/>
                </svg>
              </div>
              <div class="message-content">
                <div class="message-text">{{ message.text }}</div>
                <div class="message-time">{{ message.time }}</div>
              </div>
            </div>
            <div v-if="isLoading" class="loading-message">
              <div class="loading-avatar">
                <svg viewBox="0 0 24 24" fill="currentColor">
                  <path d="M2 18v2h20v-2H2zm1-3h18l1-5H2l1 5zM4 8l1-5h14l1 5H4z"/>
                </svg>
              </div>
              <div class="loading-content">
                <div class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-container">
            <input 
              v-model="inputMessage"
              @keyup.enter="sendMessage"
              placeholder="想找什么鞋子？我可以帮您推荐款式、查询尺码和库存..."
              class="message-input"
              :disabled="isLoading"
            />
            <button 
              @click="sendMessage" 
              class="send-button"
              :disabled="isLoading || !inputMessage.trim()"
            >
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </transition>


  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useXunfeiAIStore } from '@/stores/xunfeiAI'
import { storeToRefs } from 'pinia'
import { chatWithSpark } from '@/api/sparkService.js'

// 状态管理
const xunfeiStore = useXunfeiAIStore()
const { isOpen, messages, isLoading } = storeToRefs(xunfeiStore)

// 连接状态
const isConnected = ref(true)
const inputMessage = ref('')
const messagesContainer = ref(null)

// 切换AI面板
const toggleAI = (event) => {
  console.log('AI悬浮按钮被点击，当前状态:', isOpen.value)
  console.log('点击事件对象:', event)
  console.log('点击目标元素:', event.target)
  console.log('当前时间:', new Date().toLocaleString())
  xunfeiStore.toggleAI()
}

// 关闭AI
const closeAI = () => {
  xunfeiStore.closeAI()
}



// 检查AI连接状态
const checkAIConnection = async () => {
  try {
    const response = await fetch('/spark', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer rFanHQUBkEOUbZnjUOoB:tzOSJAWvogCYsgkbXkcW'
      },
      body: JSON.stringify({
        model: 'x1',
        messages: [{ role: 'user', content: '测试连接' }],
        user: '10284711用户',
        stream: false,
        temperature: 0.7,
        max_tokens: 50
      })
    });
    isConnected.value = response.ok;
  } catch (error) {
    console.warn('AI连接检查失败:', error);
    isConnected.value = false;
  }
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message || isLoading.value) return

  // 添加用户消息
  xunfeiStore.addMessage({
    text: message,
    isUser: true
  })
  
  inputMessage.value = ''
  xunfeiStore.isLoading = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    // 构建消息历史用于API调用
    const messageHistory = messages.value
      .filter(msg => msg.text !== '您好！我是讯飞AI助手，有什么可以帮助您的吗？')
      .map(msg => ({
        role: msg.isUser ? 'user' : 'assistant',
        content: msg.text
      }))

    // 调用星火API
    const response = await chatWithSpark([
      ...messageHistory,
      { role: 'user', content: message }
    ])

    // 处理响应
    const combinedContent = response.join('')
    
    if (combinedContent) {
      xunfeiStore.addMessage({
        text: combinedContent,
        isUser: false
      })
    } else {
      xunfeiStore.addMessage({
        text: '我正在努力思考中...让我重新组织一下语言。',
        isUser: false
      })
    }
  } catch (error) {
    console.error('AI调用失败:', error)
    xunfeiStore.addMessage({
      text: '我正在努力思考中...让我重新组织一下语言。',
      isUser: false
    })
  } finally {
    xunfeiStore.isLoading = false
    await nextTick()
    scrollToBottom()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 生命周期
onMounted(() => {
  console.log('讯飞AI助手已加载')
  // 初始化状态管理
    xunfeiStore.initialize()
    
    // 检查AI连接状态
    checkAIConnection()
    
    // 添加全局点击测试
    document.addEventListener('click', (event) => {
      console.log('全局点击事件触发:', event.target)
      if (event.target.closest('.ai-float-button')) {
        console.log('点击了AI悬浮按钮区域')
      }
    })
    
    // 延迟绑定原生点击事件
    setTimeout(() => {
      const aiButton = document.querySelector('.ai-float-button')
      if (aiButton) {
        console.log('找到AI悬浮按钮元素，绑定原生点击事件')
        aiButton.addEventListener('click', (event) => {
          console.log('原生点击事件触发！')
          event.stopPropagation()
          toggleAI(event)
        })
      } else {
        console.log('未找到AI悬浮按钮元素')
      }
    }, 1000)
})
</script>

<style scoped>
/* 悬浮按钮样式 - 鞋城主题 */
.ai-float-button {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  box-shadow: 0 6px 25px rgba(255, 107, 107, 0.4);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 10000;
  border: 3px solid rgba(255, 255, 255, 0.9);
  outline: none;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}

.ai-float-button:hover {
  transform: translateY(-3px) scale(1.08);
  box-shadow: 0 8px 30px rgba(255, 107, 107, 0.6);
  border-color: rgba(255, 255, 255, 1);
}

.ai-status-indicator {
  position: absolute;
  top: 5px;
  right: 5px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff4757;
  border: 2px solid white;
  transition: all 0.3s ease;
}

.ai-status-indicator.connected {
  background: #2ed573;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(46, 213, 115, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(46, 213, 115, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(46, 213, 115, 0);
  }
}

.ai-icon {
  width: 30px;
  height: 30px;
  color: white;
  animation: float 3s ease-in-out infinite;
}

.ai-pulse {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: rgba(255, 107, 107, 0.3);
  animation: pulse 2s infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-5px); }
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  100% { transform: scale(1.3); opacity: 0; }
}

/* 聊天面板样式 */
.ai-chat-panel {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 380px;
  height: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  z-index: 10001;
  overflow: hidden;
}



/* 面板头部 - 鞋城主题 */
.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18px 20px;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  color: white;
  box-shadow: 0 2px 10px rgba(255, 107, 107, 0.3);
}

.header-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.ai-avatar {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.minimize-btn, .close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.minimize-btn:hover, .close-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

/* 聊天内容区 */
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.messages-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  color: white;
}

.message-content {
  max-width: 240px;
}

.message-text {
  padding: 12px 16px;
  border-radius: 18px;
  background: #f0f2f5;
  color: #333;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
}

.user-message .message-text {
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  color: white;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

/* 加载状态 */
.loading-message {
  display: flex;
  gap: 12px;
  align-items: center;
}

.loading-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 6px;
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes loading {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

/* 输入区域 - 鞋城主题 */
.input-area {
  padding: 16px 20px;
  border-top: 1px solid #ffe0e0;
  background: linear-gradient(to bottom, #fff5f5, #ffffff);
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.message-input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ffd1d1;
  border-radius: 24px;
  background: white;
  font-size: 14px;
  outline: none;
  transition: all 0.2s ease;
}

.message-input:focus {
  border-color: #FF6B6B;
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.2);
}

.send-button {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background: linear-gradient(135deg, #FF6B6B 0%, #FF8E53 100%);
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.send-button:hover:not(:disabled) {
  transform: scale(1.1);
  box-shadow: 0 2px 12px rgba(255, 107, 107, 0.4);
}

.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}



/* 过渡动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}

.slide-fade-enter-active, .slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from, .slide-fade-leave-to {
  transform: translateY(20px) scale(0.95);
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .ai-chat-panel {
    width: 90vw;
    height: 70vh;
    right: 5vw;
    left: 5vw;
    bottom: 20px;
  }
  
  .ai-float-button {
    bottom: 20px;
    right: 20px;
    width: 56px;
    height: 56px;
  }
}
</style>